import axios from "axios";
import router from '../router'
import storageUtil from '../utils/localstorage'
// import Loading from 'element-plus/lib/components/loading'
import ElMessage from 'element-plus/lib/components/message'

let config = {
	baseURL: '',
	timeout: 10000
}
//创建实例
let instance = axios.create(config)
// let loading = {};
//请求拦截器
instance.interceptors.request.use(config => {
	let userId = storageUtil.get("userId");
	let token = storageUtil.get("token");
	if (userId) {
		config.headers.userId = userId;
		config.headers.token = token;
		// config.headers={"userId":userId,"token":token};
	}
	// loading = Loading.service({
	// 	fullscreen: true,
	// 	text: "数据加载中..."
	// }) //显示加载效果
	return config; //拦截器里一定要返回config, 不然请求无法发送出去。
})
//响应拦截器
instance.interceptors.response.use(resp => {
	// loading.close();
	if (resp.status === 200) {
		let data = resp.data;
		console.log("code="+data.code)
		if (data.code === 2) {
			ElMessage({
				showClose: true,
				message: data.msg,
				type: 'warning'
			});
			router.push("/login")
		} else if (data.code === 0) {
			return data;
		} else if (data.code === 5) {
			return data;
		} else {
			console.log("data="+data)
			//弹出框显示后台返回的错误信息
			ElMessage({
				showClose: true,
				message: data.msg,
				type: 'warning'
			});
			return data;
		}
	}
	// let data = resp.data;
	// alert(data)
	// if (data == "401 Unauthorized.(没有权限)" || data == "no login") {
	// 	//弹出框显示后台返回的错误信息
	// 	ElMessage({
	// 		showClose: true,
	// 		message: "warning: " + data,
	// 		type: 'warning'
	// 	});
	// 	router.push("/login")
	// }else{
	// 	return data;
	// }
}, error => {
	//请求发生异常
	// loading.close();
	return Promise.reject("error: "+error);
})

let http = {
	install(app) {
		app.config.globalProperties.$axios = instance;
	}
}
export default http;
